var quotationPreviewObj = {},
	correctionParam = {},
	isPrintFlag = "0",
	newDicts = {};

var policyInfo = {}; // 保单信息
var policyTypes = [];

var dataDictionary = {
	'plateType': '495',
	'palteColor': '109',
	'useProperties': 'VEH81175',
	'carType': 'VEH74001',
	'carUse': 'VEHICLEPURPOSE2015',
	'useDetail': 'vehicleUsageDetail',
	'specialVehicleIden': 'VEH81006',
	'isCarInsure': 'VEHICLEUSAGEDETAILTYPE',
	'relationship': 'VEH81030',
	'holderRelationship': 'VEH81030',
	'energyType': 'VEH81111',
	'ownerNature': 'OWNERPROP',
	'holderCerType': '112',
	'insureCerType': '112',
	'claimCerType': '112',
	'draweeCertificatetype': '112',
	'cerType': '112',
	'insureRelationship': 'VEH81040',
	'invoiceType': 'invoiceType',
	'taxpayerType': 'taxPayerCertType',
	'taxVehicleType': 'taxVehicleType',
	'taxpayerNational': 'nationality',
	'taxPlateType': 'taxPlateType',
	'vehicleSettledAddr': 'vehicleSettledDownAddr.tj',
	'taxTicketType': 'taxReceiptType',
	'taxFuelType': 'taxFuelType',
	'taxVehicleProp': 'taxVehicleUsageProps',
	'taxVehicleCode': 'taxVehicleStyle',
	'vehicleStreetCode': 'vehicleSettledDownAddr.tj',
	'taxNonlocalBureau': 'taxNonlocalBureau',
	'tpyRiskflagName': 'tpyRiskFlag',
	'vehicleInspection': 'vehicleInspection',
	'pmVehicleType': 'vehicle.style',
	'taxCustomerType': 'customerType',
	'taxBureauNametj': 'taxBureauName.tj',
	'deductionDueType': 'taxScheme',
	'deductionDueCode': 'deductionDueCode',
	'payWay': 'pay.type.conf',
	'jqinsuranceCarriers': 'jqinsurance_carriers'
};

// 车船税字段
function getTaxData() {
	var v3Data = {
		'taxpayerName': '纳税人姓名',
		'taxpayerRecno': '纳税人识别号',
		'taxType': '纳税类型',
		'taxBureau': '税务机关代码',
		'stTaxStartDate': '车船税起期',
		'stTaxEndDate': '车船税止期',
		'taxBureauName': '税务机关名称',
		'deductionDueType': '减免税方案代码',
		'deductionDueCode': '减免税原因代码',
		'reductionAmount': '减免税金额',
		'deductionDueProportion': '减免比例',
		'reductionNo': '减免凭证号',
		'taxPaidNo': '完税凭证号',
		'registryNumber': '税务登记证号'
	};
	var localData = {
		'taxpayerName': '纳税人姓名',
		'taxCustomerType': '纳税人类型',
		'taxpayerType': '证件类型',
		'taxpayerNo': '证件号码',
		'taxType': '纳税类型',
		'stTaxStartDate': '车船税起期',
		'stTaxEndDate': '车船税止期',
		'taxBureauName': '税务机关名称',
		'totalWeight': '总质量(公斤)',
		'deductionDueCode': '减免税原因代码',
		'reductionAmount': '减免金额',
		'reductionNo': '减免凭证号',
		'taxPaidNo': '完税凭证号'
	};

	if ( $.pageContext.currentUser.branchCode == '3090100' ) {
		v3Data[ 'stTaxBackAmount' ] = '车船税补退费';
		localData[ 'stTaxBackAmount' ] = '车船税补退费';
	}

	if ( $.pageContext.consts.STRATEGY_VEHICLE_TAX == '1' ) {
		return v3Data;
	} else if ( $.pageContext.consts.STRATEGY_VEHICLE_TAX == '2' ) {
		return localData;
	}
}

function differenceData() { return {}; };

function taxChange() {};
function encryptionInfo( response ) {};
function isDrawee() {
	return false;
}
function taxVehicleTypeDicts() {};

$(function(){
	$.initContext({
		pageCode: "quotation_preview",
		dictCodes:["495", "109", "VEH81175", "VEH74001", "VEHICLEPURPOSE2015", "vehicleUsageDetail", "VEH81006", "VEHICLEUSAGEDETAILTYPE",
			"VEH81030", "VEH81111", "OWNERPROP", "112", "business.conf", "invoiceType", "VEH81040", "batch.status.conf", "09batch.type.conf",
			"taxVehicleType","taxVehicleType.sh","nationality","taxPlateType","vehicleSettledDownAddr.tj","taxReceiptType",
			"taxFuelType","taxVehicleUsageProps","taxTypeCode","taxRegistrationCertNo","taxPayerCertType","taxBureauName.tj","taxVehicleStyle", "taxNonlocalBureau",
			"tpyRiskFlag", "vehicleInspection", "vehicle.style", "customerType", "deductionDueCode", "taxScheme", "pay.type.conf", "jqinsurance_carriers"
		],
		dataLoadedCallback: function () {
			if ($.pageContext.consts.ENABLE_PAPERLESS_INSURANCE == '1' ) {
				initElectronicPolicy();
				initElectronicPolicyOpt();
			}
			if($.pageContext.consts.NEED_ELECTRIC_APPLICATION_OPTION == "1"){
				initElectronicApplication();
			}

			pageDifferenceOff();
			MainGlobal.initDifferenceInfo();
			differenceFieldView(differenceData());
			taxView(getTaxData());
			initDicts();
			printSelect();
			if ( isDrawee() ) {
				addDraweeInfo();
			}
			initialiseData();

			// 历史预览 加载打印下拉框
			if ( getAnchor().indexOf("&") != "-1" ) historyPrintSelect();

			if(!$.pageContext.currentUser.partnerType || $.pageContext.currentUser.partnerType != 3){
				$("[data='lifeInsurancePer']").prev().remove();
				$("[data='lifeInsurancePer']").remove();
				$("[data='lifeAgentFlag']").prev().remove();
				$("[data='lifeAgentFlag']").remove();
			}
		},
		ajaxStartCallback: showLoading
	});

	function initialiseData() {

		setTime($.pageContext.userConfigs.currentDate);
		var accidentPremiumHtml = '<label class="control-label col-md-2 isAccEPolicy"></label>\
		<div class="form-control-static isAccEPolicy col-md-4"></div><label class="control-label isAccEPolicy col-md-2">是否发送意外险电子保单</label>\
		<div class="form-control-static isAccEPolicy col-md-4" data="isAccEPolicy"></div><div class="clearfix isAccEPolicy"></div>\
		<label class="control-label  col-md-2"></label>\
		<div class="form-control-static col-md-4"></div>\
		<label class="control-label  col-md-2">意外险保费</label>\
		<div class="form-control-static col-md-4" data="accidentPremium"></div>\
		<div class="clearfix"></div>';

		if($.pageContext.consts.ALLOW_ACCIDENT_INSURANCE == 1){
			$("#accidentPremiumTab").replaceWith(accidentPremiumHtml);
			$('#containAccidentText').show();
		}

		if($.pageContext.consts.STRATEGY_VEHICLE_TAX != 2){
			$(".local-show").hide();
		}

		if(window.location.href.indexOf("#")!=-1){

			$("#quotationNo").val(getAnchor());
			$("#billCode").text(getAnchor());

			var param = {};
			var searchUrl = "";
			if (getAnchor().indexOf("&") != "-1"){

				if ($.pageContext.consts.ALLOW_QUERY_CORRECTION_INFO == '1') {
					$('#barchInfo').css('display', 'block');
				}

				$("#print").siblings().hide();
				if ( $("#policyReissue").length != 0 ) {
					$("#policyReissue").show();
				}

				if ( $("#policyDownLoad").length != 0 ) {
					$("#policyDownLoad").show();
				}

				if ( $("#insureDown").length != 0 ) {
					$("#insureDown").show();
				}

				if ( $("#insureReissue").length != 0 ) {
					$("#insureReissue").show();
				}

				$("#print").attr("status","spec");
				var arr = getAnchor().split("&");
				var state = arr.pop().split("%")[1];
				$("#state").val(state);
				param = {
					"meta":{},
					"redata":{}
				};
				searchUrl = "history/historyPreview";

				for (var i = 0; i < arr.length; i++) {
					param.redata[arr[i].split("%")[0]] = arr[i].split("%")[1] == "undefined" ? "" : arr[i].split("%")[1];
				}

				$("#resultTable thead tr th:last").remove();
				$(".tbClone tbody tr td:last").remove();

				$('#containAccidentText').hide();
				$('[data="accidentPremium"]').prev().prev().prev().remove();
				$('[data="accidentPremium"]').prev().prev().remove();
				$('[data="accidentPremium"]').prev().remove();
				$('[data="accidentPremium"]').remove();
				$('[data="accidentPremium"]').next().remove();

			} else {
				param = {
					"meta":{},
					"redata":{quotationNo:getAnchor()}
				};
				searchUrl = "quotationPreview/queryQuotationPreview";
			}

			cpic_ajax({
				url:searchUrl,
				data:param,
				success:function(response){

					if ( response.result.insuranceVo && response.result.insuranceVo.taxType ) {
						taxChange(response);
					}

					MainGlobal.cerNo = response.result.holdVo.holderCerNo || '';

					// 加密数据
					encryptionInfo( response );

					var carInfoVo = response.result.carInfoVo || {};
					var claimPerson = response.result.claimPerson || {};
					var holdVo = response.result.holdVo || {};
					var insuranceVo = response.result.insuranceVo || {};
					var insureVo = response.result.insureVo || {};

					if(!insuranceVo.isAccEPolicy){
						$(".isAccEPolicy").remove();
					}

					dataRel(carInfoVo, 'carInfoVo');
					dataRel(claimPerson, 'claimPerson');
					dataRel(holdVo, 'holdVo');
					dataRel(insuranceVo, 'insuranceVo');
					dataRel(insureVo, 'insureVo');

					// 开票人信息
					if ( isDrawee() ) {
						var drawee = response.result.drawee || {};

						dataRel(drawee, 'drawee');

						$.each(response.result.drawee,function(key,value){
							$("[data="+key+"]").text(value);
						});

						if( response.result.drawee.isRequireDrawee && response.result.drawee.isRequireDrawee == "1"){
							$("input[name='isRequireDrawee']").attr("checked","true");
						}
					}

					if ( response.result.policyNoTypes ) {
						policyNoTypesAnalyze( response.result.policyNoTypes );
					}


					// 字段替换
					function dataRel(data, name) {
						$.each(data, function(key, value) {
							if (key in dataDictionary) {
								if (newDicts[dataDictionary[key]]) {
									response.result[name][key] = newDicts[dataDictionary[key]][value];
								}

							}
						});
					}

					(typeof queryPreview == "function")?queryPreview(response):"";

					if($.pageContext.consts.NEED_ELECTRIC_INVOICE_OPTION != 1){
						$("[name='createInvoice']").parent("div").remove();
					}

					if($.pageContext.consts.NEED_ELECTRIC_APPLICATION_OPTION != 1){
						$("[name='isEApplication']").parent("div").remove();
					}

					if($.pageContext.userConfigs.isPerformance == undefined || $.pageContext.userConfigs.isPerformance == '0'){

						$("[data='syperformance']").parent().remove();
						$("[data='jqperformance']").parent().remove();
					}
					if($.pageContext.userConfigs.isBusinessfee == undefined || $.pageContext.userConfigs.isBusinessfee == '0'){
						$("[data='jqbusinessfee']").parent().remove();
						$("[data='sybusinessfee']").parent().remove();
					}
					if($.pageContext.userConfigs.isPoudage == undefined || $.pageContext.userConfigs.isPoudage == '0'){

						$("[data='businesspoudage']").parent().remove();
						$("[data='trafficpoudage']").parent().remove();
					}

					if($.pageContext.consts.IS_CHECK_DUAL_RECORD == undefined || $.pageContext.consts.IS_CHECK_DUAL_RECORD == '0'){
						$("[data='dualRecordSalesName']").prev().remove();
						$("[data='dualRecordSalesName']").remove();
						$("[data='dualRecordSalesIdCard']").prev().remove();
						$("[data='dualRecordSalesIdCard']").remove();
					}

					if( response.result.carInfoVo.createEpolicy && response.result.carInfoVo.createEpolicy == "1"){
						$("input[name='createEpolicy']").attr("checked","true");
						MainGlobal.createEpolicy = response.result.carInfoVo.createEpolicy;
					}

					if( response.result.carInfoVo.isEApplication && response.result.carInfoVo.isEApplication == "1"){
						$("input[name='isEApplication']").attr("checked","true");
						MainGlobal.isEApplication = response.result.carInfoVo.isEApplication;
					}

					if( response.result.carInfoVo.createInvoice &&  response.result.carInfoVo.createInvoice == "1"){
						$("input[name='createInvoice']").attr("checked","true");
					}
					if( response.result.carInfoVo.sendEpolicy && response.result.carInfoVo.sendEpolicy == "1"){
						$("input[name='sendEpolicy']").attr("checked","true");
					}
					if( response.result.insureVo.issueInvoice && response.result.insureVo.issueInvoice == "1"){
						$("input[name='issueInvoice']").attr("checked","true");
					}
					if (response.result.taxpayerInfoVo) {
						createTable(response.result.taxpayerInfoVo,$("#vehicleAndVesselTaxResultTable"),$("#vehicleAndVesselTaxTbClone"));
					}
					if (response.result.list) {
						createTable(response.result.list,$("#resultTable"),$(".tbClone"));

						if (response.result.list.length != 0) {
							for (var i = 0; i < response.result.list.length; i++) {
								$.each(response.result.list[i], function(key, val) {
									if (val == 'damageCardeductibles' && response.result.list[0].factorValue != 0) {
										$('#resultTable tbody').find('tr').eq(0).find('td').eq(0).append('<a style="float:none">('+response.result.list[0].factorName+response.result.list[0].factorValue+' 元</a>)');
										//$('#resultTable tbody').find('tr').eq(0).find('td').eq(1).append('<p style="float:none">'+response.result.list[0].factorValue+' 元</p>');
									}
									else if (val == 'seat') {
										$('#resultTable tbody').find('tr').eq(i).find('td').eq(1).text(response.result.list[i].insuranceAmount+' 元 X' + response.result.list[i].factorValue+'座');
									}
									else if (val == 'maxClaimDays') {
										$('#resultTable tbody').find('tr').eq(i).find('td').eq(1).text(response.result.list[i].insuranceAmount+' 元 X' + response.result.list[i].factorValue+'天');
									}
									else if (val == 'repairFactorRate') {
										$('#resultTable tbody').find('tr').eq(i).find('td').eq(1).html(response.result.list[i].insuranceAmount+' ' + '费率：'+response.result.list[i].factorValue);
									}
									else if (val == 'producingArea') {
										$('#resultTable tbody').find('tr').eq(i).find('td').eq(1).html(response.result.list[i].insuranceAmount+' ' + '产地：'+coveageAdd(response.result.list[i].factorValue));
									}
								});
							}
						}
					}

					createTable(response.result.commercialAgreementVo,$("#commericalTable"),$(".commericalTbClone"));

					$("#CompulsoryAggrementContent").html(response.result.compulsoryAggrementVo.content || "");
					$("#commercialSpecialAggrement").html(response.result.insuranceVo.commercialSpecialAggrement || "");
					$("#lawsuitsOrg").val(response.result.carInfoVo.lawsuitsOrg);
					$("#lawsuits").text(response.result.carInfoVo.lawsuits || "");

					$.each(response.result.insuranceVo,function(key,value){
						if(key == "poudage"){
							var oVal = value == "" ? "" : value * 100 + " %";
							$('div').find("[data='poudage']").text(oVal);
						}else{
							$("div[data="+key+"]").text(value);
							$("span[data="+key+"]").text(value);
						}
						if(key == 'accidentInfo' && key !== ''){
							$('#accidentInfo').text(value);
						}

						$("[tax-data="+key+"]").text(value);
					});

					$.each(response.result.networkVo,function(key,value){
						$('div').find("[data="+key+"]").text(value);
					});
					$.each(response.result.holdVo,function(key,value){
						$('div').find("[data="+key+"]").text(value);
					});
					$.each(response.result.insureVo,function(key,value){
						$("[data="+key+"]").text(value);
					});

					if (response.result.claimPerson) {
						$.each(response.result.claimPerson,function(key,value){
							$('div').find("[data="+key+"]").text(value);
						});
					}
					$("[data='tonnage']").text('');

					$.each(response.result.carInfoVo,function(key,value){
						$("[data="+key+"]").text(value);
					});
					if($("[data='engineNo']").width() > 188.88){
						$(".clearfix-registDate").addClass("clearfix");
					}

					$("#print").attr("status",response.result.carInfoVo.status);

					if (getAnchor().indexOf("&") != "-1") {

						quotationPreviewObj.businessPrintVo = response.result.businessPrintVo || {};
						quotationPreviewObj.trafficPrintVo = response.result.trafficPrintVo || {};
						quotationPreviewObj.applicationNo = response.result.applicationNo || "";
						quotationPreviewObj.policyNo = response.result.policyNo || "";
						quotationPreviewObj.policyType = response.result.policyType || "";

						correctionParam.policyNo = response.result.policyNo || "";
						correctionParam.applicationNo = response.result.applicationNo || "";
						if (response.result.InsurancesVo) {
							correctionParam.originType = response.result.InsurancesVo.originType || "";
						}

						if (response.result.businessPrintVo && response.result.businessPrintVo.productCode) {
							correctionParam.productCode = response.result.businessPrintVo.productCode;
						} else if (response.result.trafficPrintVo && response.result.trafficPrintVo.productCode) {
							correctionParam.productCode = response.result.trafficPrintVo.productCode;
						}
						if ( response.result.holdVo.holderEmail ) {
							correctionParam.email = response.result.holdVo.holderEmail;
						} else {
							correctionParam.email = '';
						}


						correctionParam.taxType = $("[tax-data='taxType']").text();
						correctionParam.taxPaidNo = $("[tax-data='taxPaidNo']").text();

						policyTypes = [{
							'policyNo': correctionParam.policyNo,
							'applicationNo': correctionParam.applicationNo,
							'policyStatus': '7'}];
					}
				}

			},true);
		}
	}

	//打印
	if (getAnchor().indexOf("&") != "-1"){
		$("#print").click(function(){
			var quotationStateOpt = $("#print").attr("status");
			var quotationNo = getAnchor();
			historyPrint(quotationStateOpt, quotationNo);
		});
	} else {
		$("#print").click(function(){
			var quotationStateOpt = $("#print").attr("status");
			var quotationNo = getAnchor();
			searchPreviewPrint(quotationStateOpt,quotationNo);
		});
	}

	//发送
	$("#notePrompt").click(function(){
		if(!getAnchor()){
			dialogs.warning("报价单号不存在!",warningTittle);
			return false;
		}
		notePromptFn(getAnchor());
	});

	//平台查询
	$("#platformQuery").click(function(){
		window.open("../common/platform_search.html#" + getUrlParam());
	});

	//文件上传
	$("#fileUpload").click(function(){
		window.open("../file_upload/file_upload.html#" + getUrlParam());
	});

	//审核
	$("#audit").click(function(){
		window.open("../common/auditInfo.html#" + getUrlParam());
	});

	//复制
	$('#copy').click(function(){
		copyFn(getAnchor());
	});

	//发起通融
	$('#quest').click(function(){
		cpic_ajax({
			url:"/quotationPreview/sendAccommodationPreview",
			data:{
				"meta":{},
				"redata":{quotationNo:getAnchor()}
			},
			success:function(response){
				if(response.message.code == "success"){
					dialogs.notify("申诉已提交审核，请耐心等待！",notifyTittle);
					$('#query-side').show();
					$('#quest').hide();
					return;
				}else{
					dialogs.warning("该状态下不能进行申诉",warningTittle);
					return;
				}
			}
		},true);
	});

	var timeAccout = 0;
	//通融查询
	$('#query-side').click(function(){

		if(!timeAccout){
			cpic_ajax({
				url:"/quotationPreview/queryAccommodationPreview",
				data:{
					"meta":{},
					"redata":{quotationNo:getAnchor()}
				},
				success:function(response){
					if(response.message.code == "success"){
						dialogs.notify("通融查询成功",notifyTittle);
						$('#query-side').hide();
						return;
					}else{
						dialogs.warning("通融查询失败",warningTittle);
						return;
					}
				}
			},true);
		}else{
			dialogs.warning("通融查询时间间隔不得低于10秒",warningTittle);
			return;
		}
		var timer = setInterval(function(){
			if(timeAccout == 10){
				clearInterval(timer);
				timeAccout = 0;
			}else{
				timeAccout++;
			}
		},1000);

	});

	$('#barchInfo').on('click', function() {

		if (getAnchor().indexOf("&") != "-1") {
			var policyNo = correctionParam.policyNo || '';
			var applicationNo = correctionParam.applicationNo || '';
			var originType = correctionParam.originType || '';
			var productCode = correctionParam.productCode || '';
			var email = correctionParam.email || '';
			var cerNo = MainGlobal.cerNo || '';
			var createEpolicy = MainGlobal.createEpolicy || '';
			var taxType = correctionParam.taxType || '';
			var taxPaidNo = correctionParam.taxPaidNo || '';
			var plateNo = $("[data='plateNO']").text() || '';

			var urlParam = "policyNo%" + policyNo
				+ "&applicationNo%" + applicationNo
				+ "&originType%" + originType
				+ "&productCode%" + productCode
				+ "&cerNo%" + cerNo
				+ "&createEpolicy%" + createEpolicy
				+ "&email%" + email
				+ "&taxType%" + taxType
				+ "&taxPaidNo%" + taxPaidNo
				+ "&plateNo%" + plateNo;

			window.open("../correction_info/correction_info.html#" + setBase64(urlParam));
		}
	});

	function coveageAdd(val){
		if(val == '0')
			return "国产";
		else if(val == '1')
			return "进口";
		return "";
	}

	//电子投保单下载
	$('body').on('click', '#insureDown',function() {
		if(!policyTypes[0]){
			return false;
		}

		if ( policyTypes[0].policyStatus != '7' ) {
			dialogs.warning('该保单还未生效，请核实！', warningTittle);
			return false;
		}

		if ( MainGlobal.isEApplication == '0' ) {
			dialogs.warning('该保单不为电子投保单!无法下载.', warningTittle);
			return false;
		}

		if ( policyTypes.length == '2' ) {
			insureDown( policyInfo.commercial.applicationNo );
		} else {
			insureDown( policyTypes[0].applicationNo );
		}

	});

	//电子投保单补发
	$('body').on('click', '#insureReissue',function() {
		if(!policyTypes[0]){
			return false;
		}

		if ( policyTypes[0].policyStatus != '7' ) {
			dialogs.warning('该保单还未生效，请核实！', warningTittle);
			return false;
		}

		if ( MainGlobal.isEApplication == '0' ) {
			dialogs.warning('该保单不为电子投保单!无法补发.', warningTittle);
			return false;
		}

		if($("[data='holderEmail']").text() == ""){
			dialogs.warning("补发电子邮箱为空，请批改后再试！", warningTittle);
			return;
		}

		var oAppNo;
		if ( policyTypes.length == '2' ) {
			oAppNo = policyInfo.commercial.policyNo;
		} else {
			oAppNo = policyTypes[0].policyNo;
		}

		cpic_ajax({
			url:"insuredNo/reissueEpolicy",
			data: {"meta":{},"redata": {
				insureNo: oAppNo
			}},
			success:function(response){
				dialogs.notify(response.message.message, notifyTittle );
			}
		},true);

	});
});

function historyPrint() {
	var pageOn = new IndigoSoftware.PageOn();
	MainGlobal.print.isPrintFlag = "0";

	if ($("#state").val() != "3") {
		dialogs.warning("只有生效保单才可打印!",warningTittle);
		return false;
	}

	$("#printDialog").show(0, function(){
		var printSelets = [];
		var _this = $(this);


		$("#slipYearSeq").val("");
		$("#slipYearSeqWarp").hide();

		// var selData = [{"code":"08","name":"投保单"},
		//             {"code":"09","name":"浮动告知书"},
		// 			{"code":"03","name":"商业险保单"},
		// 			{"code":"02","name":"交强险保单"},
		// 			{"code":"04","name":"商业险服务卡"},
		// 			{"code":"06","name":"交强险标志"}],
		// option93 = {"code":"93","name":"意外险投保单"};

		// if ($.pageContext.consts.ALLOW_ACCIDENT_INSURANCE == "1") {
		// 	selData.push(option93);
		// }

		// 生效打印有效单证
		// if ( $("#state").val() == '3' ) {

		// 	printSelets = MainGlobal.print.historyPrintSelects.default;
		// } else {
		// 	printSelets = MainGlobal.print.historyPrintSelects.noPrice;
		// }

		var printSelets = MainGlobal.print.historyPrintSelects.hDefault;

		createOption($("#billType"),printSelets);

		$("#billType").change(function(){
			MainGlobal.print.isPrintFlag = "0";
			switch ($(this).val()) {
				case "03":
					$("#slipYearSeqWarp").show();
					$("#slipYearSeq").val($.pageContext.consts.COMMERCIAL_POLICY_DOC_CODE);
					break;
				case "02":
					$("#slipYearSeqWarp").show();
					$("#slipYearSeq").val($.pageContext.consts.COMPULSORY_POLICY_DOC_CODE);
					break;
				case "06":
					$("#slipYearSeqWarp").show();
					$("#slipYearSeq").val($.pageContext.consts.COMPULSORY_POLICY_MARK_CODE);
					break;
				default:
					$("#slipYearSeqWarp").hide();
					$("#slipYearSeq").val("");
					break;
			}
		});

		_this.find(".confirm").bind("click",function(){
			var printType = $("#billType").val();
			var slipYearSeq = $("#slipYearSeq").val();

			if($("#billType").val() == '03' || $("#billType").val() == '02' || $("#billType").val() == '06'){
				if ($.trim(slipYearSeq) == '' || slipYearSeq.length != 14 || !/^[a-zA-Z0-9]+$/g.test(slipYearSeq)) {
					dialogs.warning("单证流水号长度不为14位或包含特殊字符！",warningTittle);
					return false;
				}
			}

			var params = parasFn(printType, slipYearSeq);
			params.redata.isPrintFlag = MainGlobal.print.isPrintFlag;

			// cpic_ajax({
			//           url: "print/history09Policy",
			//           data: params,
			//           success: function(response){

			//           	if($("#slipYearSeq").length != 0 && $("#slipYearSeq").val() != "") {
			//           		doPrint(pageOn, response.result, 0, params, "history");
			//           	} else {
			//           		doPrint(pageOn, response.result, 0, null, "history");
			//           	}

			//           }
			//       },true);


			ajaxPost({
				url: "print/history09Policy",
				data: params,
				success: function(response){

					if (response.message.code === "failed") {
						dialogs.warning(response.message.message,"请求出错");
						return false;
					}

					if (response.result && response.result.isPrintFlag) {
						MainGlobal.print.isPrintFlag = response.result.isPrintFlag;
					}


					if (response.message.code == "printFailed" || response.message.code == "success" && MainGlobal.print.isPrintFlag == "1") {

						var close = function() {
							$(".noticeDialog").remove();
							MainGlobal.print.isPrintFlag = "0";
						};

						dialogs.warning(response.message.message, warningTittle, ["yes","no"], function() {
							closeDialog();
							params.redata.isPrintFlag = MainGlobal.print.isPrintFlag;

							ajaxPost({
								url: "print/history09Policy",
								data: params,
								success: function(response){
									MainGlobal.print.isPrintFlag = "0";
									if(response.message.code != 'success'){
										dialogs.warning(response.message.message,"请求出错");
										return false;
									}

									if($("#slipYearSeq").length != 0 && $("#slipYearSeq").val() != "") {
										doPrint(pageOn, response.result, 0, params, "history");
									} else {
										doPrint(pageOn, response.result, 0, null, "history");
									}

								}
							},true);

						},close);

					} else {

						if($("#slipYearSeq").length != 0 && $("#slipYearSeq").val() != "") {
							doPrint(pageOn, response.result, 0, params, "history");
						} else {
							doPrint(pageOn, response.result, 0, null, "history");
						}

					}

				}
			},true);
		});

		_this.find(".preview").bind("click",function(){
			var printType = $("#billType").val();
			var slipYearSeq = $("#slipYearSeq").val();

			if($("#billType").val() == '03' || $("#billType").val() == '02' || $("#billType").val() == '06'){
				if ($.trim(slipYearSeq) == '' || slipYearSeq.length != 14 || !/^[a-zA-Z0-9]+$/g.test(slipYearSeq)) {
					dialogs.warning("单证流水号长度不为14位或包含特殊字符！",warningTittle);
					return false;
				}
			}

			var params = parasFn(printType, slipYearSeq);

			cpic_ajax({
				url: "print/history09Policy",
				data: params,
				success: function(response){
					doPrint(pageOn, response.result, 1);
				}
			},true);

		});

		_this.find(".canel").bind("click",function(){
			_this.hide();
			_this.find(".o-c-btn").unbind("click");
		});

		function parasFn(printType, slipYearSeq) {

			var vo = {},
				obj = {};

			if(printType == '03' || printType == '04'){
				vo = quotationPreviewObj.businessPrintVo;
			}

			if(printType == '02' || printType == '06'){
				vo = quotationPreviewObj.trafficPrintVo;
			}

			if(printType == '08' || printType == '09'){
				vo = {
					applicationNo : quotationPreviewObj.applicationNo,
					policyNo : quotationPreviewObj.policyNo
				}
			}

			if (printType == '80' ) {
				vo = {
					applicationNo : quotationPreviewObj.applicationNo,
					policyNo : quotationPreviewObj.policyNo
				}
			}

			for (var i in vo) {
				obj[i] = vo[i];
			}

			obj.printType = printType;
			obj.slipYearSeq = slipYearSeq;
			obj.insuredName = $("[data=holderName]").html();
			obj.holderName = $("[data=insureName]").html();
			obj.policyType = quotationPreviewObj.policyType;

			if (printType == '08' || printType == '09'||printType == '84' || printType == '74' || printType == '16' ) {
				delete obj.insuredName;
				delete obj.holderName;
				delete obj.slipYearSeq;
			}

			return {meta: {}, redata: obj};
		}
	});

}

//初始化 dicts
function initDicts() {
	var dicts = $.pageContext.dicts;
	for (var p in dicts) {
		var obj = {};

		for (var i = 0; i < dicts[p].length; i++) {
			obj[dicts[p][i]['code']] = dicts[p][i]['name'];
		}

		newDicts[p] = obj;
	}

	taxVehicleTypeDicts( newDicts );

}

// 车辆信息视图
function differenceFieldView(data) {
	if (!data) {
		return;
	}
	var items = '';

	$.each(data, function(key, val) {

		items += '<div class="tax-item">'+
		'<label>'+val+'</label>'+
		'<div class="item-val" data="'+key+'"></div>'+
		'</div>';
	});

	$("#differenceFieldView").append(items);
}

// 车船税视图
function taxView( data ) {

	if ( !data ) {
		return;
	}

	var items = '';

	$.each(data, function(key, val) {

		items += '<div class="tax-item">'+
		'<label>'+val+'</label>'+
		'<div class="item-val" tax-data="'+key+'"></div>'+
		'</div>';
	});

	$("#taxView").append(items);
}

function initElectronicPolicyOpt() {
	$('#policyDownLoad').on('click', function() {
		if(!policyTypes[0]){
			return false;
		}

		if ( policyTypes[0].policyStatus != '7' ) {
			dialogs.warning('该保单还未生效，请核实！', warningTittle);
			return false;
		}

		if ( MainGlobal.createEpolicy == '0' ) {
			dialogs.warning('该保单不为电子保单!无法下载.', warningTittle);
			return false;
		}

		if ( policyTypes.length == '2' ) {
			policyDownLoadDialog( policyInfo );
		} else {
			policyDownLoad( policyTypes[0].policyNo );
		}

	});

	//电子投保单下载
	$('#insureDown').on('click', function() {
		if(!policyTypes[0]){
			return false;
		}

		if ( policyTypes[0].policyStatus != '7' ) {
			dialogs.warning('该保单还未生效，请核实！', warningTittle);
			return false;
		}

		if ( MainGlobal.isEApplication == '0' ) {
			dialogs.warning('该保单不为电子投保单!无法下载.', warningTittle);
			return false;
		}

		if ( policyTypes.length == '2' ) {
			insureDownDialog( policyInfo );
		} else {
			insureDown( policyTypes[0].applicationNo );
		}

	});

	$('#policyReissue').on('click', function() {
		if(!policyTypes[0]){
			return false;
		}

		if ( policyTypes[0].policyStatus != '7' ) {
			dialogs.warning('该保单还未生效，请核实！', warningTittle);
			return false;
		}

		if ( MainGlobal.createEpolicy == '0' ) {
			dialogs.warning('该保单不为电子保单!无法补发.', warningTittle);
			return false;
		}

		if (getAnchor().indexOf("&") != "-1"){

			if ( policyTypes.length == '2' ) {
				policyReissue( policyInfo.compulsory.applicationNo, policyInfo.compulsory.policyNo, $("[data='plateNO']").text(), $("[data='holderEmail']").text(), getAnchor());
			} else {
				policyReissue( policyTypes[0].applicationNo, policyTypes[0].policyNo, $("[data='plateNO']").text(), $("[data='holderEmail']").text(), getAnchor() );
			}

		} else {
			cpic_ajax({
				url:"epolicy/queryPlantNo",
				data: {"meta":{},"redata": {
					quotationNo: getAnchor()
				}},
				success:function(response){
					var plateNo = response.result.plateNo;

					MainGlobal.policyReissueData.compulsory.plateNo = plateNo;
					if ( policyTypes.length == '2' ) {	// 判断是否是大保单
						MainGlobal.policyReissueData.isBigPolicy = 1;	// 给全局赋值大保单
						MainGlobal.policyReissueData.compulsory.applicationNo = policyInfo.compulsory.applicationNo;
						MainGlobal.policyReissueData.compulsory.policyNo = policyInfo.compulsory.policyNo;
						MainGlobal.policyReissueData.compulsory.plateNo = plateNo;

						policyReissue( policyInfo.commercial.applicationNo,
							policyInfo.commercial.policyNo,
							plateNo,
							$("[data='holderEmail']").text() );

					} else {
						policyReissue( policyTypes[0].applicationNo,
							policyTypes[0].policyNo,
							plateNo,
							$("[data='holderEmail']").text() );
					}

				}
			},true);
		}


	});
}

function policyNoTypesAnalyze( data ) {
	policyTypes = data;
	for ( var i = 0; i < data.length; i++ ) {
		if ( data[i].policyType == '0' ) {
			policyInfo.commercial = data[i];
		} else if ( data[i].policyType == '1' ) {
			policyInfo.compulsory = data[i];
		}
	}
}

// 获取历史打印下拉框
function getHistoryPrintParams() {

	if ($.pageContext.consts.ALLOW_ACCIDENT_INSURANCE == '1' ) {		// 意外险

		return [
			{"code": "printHistoryType/@.historyWithAcdt.default"},		// 有价
			{"code": "printHistoryType/@.historyWithAcdt.v1"}			// 无价

		];

	}

	return [
		{"code": "printHistoryType/@.history.default"},					// 有价
		{"code": "printHistoryType/@.historyWithAcdt.v1"}				// 物件
	];
}

// 历史打印请求
function historyPrintSelect() {

	cpic_ajax({
		url: "dictionary/queryDicts",
		data: {"meta": {}, "redata": getHistoryPrintParams()},
		success: function (response) {
			var obj = {};
			var ret = response.result;

			if ( ret ) {

				obj.hDefault = ret[0].entries;
				obj.noPrice = ret[0].entries;

				MainGlobal.print.historyPrintSelects = obj;
			}

		}
	},true);
}

function addDraweeInfo() {
	var draweeInfoTitle = '<div class="pull-left text-right" style="width:18%;">\
		                    <span>添加开票人信息</span>&nbsp;&nbsp;\
		                    <input type="checkbox" name="isRequireDrawee"  disabled/>\
		                    <label for="">&nbsp;</label>\
		                </div>';

	var draweeInfoPanel = '<div class="blank-10"></div>\
					<label class="col-md-2 control-label">开票人名称</label>\
                    <div class="col-md-2 form-control-static" data="draweeName"></div>\
                    <label class="col-md-2 control-label">证件类型</label>\
                    <div class="col-md-2 form-control-static" data="draweeCertificatetype"></div>\
                    <label class="col-md-2 control-label">证件号码</label>\
                    <div class="col-md-2 form-control-static" data="draweeCertificateCode"></div>';

	$('#draweeInfoTitle').replaceWith( draweeInfoTitle );
	$('#draweeInfoPanel').replaceWith( draweeInfoPanel );
}

$("#uniformInsurance").on('mouseover', function(e) {

	var str = $.trim( $(this).text() );
	if ( str === '' ) return;

	var arr = str.split(';');
	var ul = '<ul>';

	for (var i = 0; i < arr.length; i++) {
		if ( getAnchor().indexOf("&") != "-1" ) {
			ul += '<li>' + arr[i] + '</li>';
		} else {
			var item = arr[i].split('/');
			ul += '<li>' + item[0] +'/'+ (item[1] || '') + '</li>';
		}
	}

	ul += '</ul>';

	$("#uniformDiv").append( html );

	var html = '<div id="uniformDiv">' + ul + '</div>';

	$('body').append( html );

	$('#uniformDiv').css({
		left: e.pageX + 'px',
		top: e.pageY + 'px'
	});

}).on('mouseout', function() {
	$('#uniformDiv').remove();
})

function showAlreadyTraffic() {

	var data = [
		{
			name: 'jqstartDate',
			text: '已投保交强险保险起期'
		},{
			name: 'jqendDate',
			text: '已投保交强险保险止期'
		},{
			name: 'jqinsuranceCarriers',
			text: '交强险承保公司'
		},{
			name: 'jqpolicyNo',
			text: '交强险保单号'
		}
	];

	var html = '';
	for (var i = 0, len = data.length; i < len; i++) {
		html += '<div class="tax-item">\
                    <label>'+ data[i].text +'</label>\
                    <div class="item-val" data="'+ data[i].name +'"></div>\
                </div>';
	}

	$('#commercialInfo').append( html );
}

function pageDifferenceOff() {
	if ($.pageContext.consts.IS_SHOW_COMPULSORY === '1') {
		showAlreadyTraffic();
	}
}